package org.andromeo.connectionapi;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.andromeo.ARException;
import org.andromeo.GRSession;
import org.andromeo.User;
import org.andromeo.UserFactory;
import org.andromeo.util.ARRequester;

public class FriendlistProcessor {

	private static final Pattern useritemPattern = Pattern.compile("<tr.*</tr>");

	/*
	 * group(1) : user id group(2) : account status (deleted or not) group(3) :
	 * username
	 */
	private static final Pattern usernamePattern = Pattern
			.compile("<a.*?set=(\\d*).*?class=\"(pop username.*?)\".*?>(.*?)</a>");

	/*
	 * group(1) : contains the online class group(2) : case group(1) contains
	 * "isnotonline" you find a date here
	 */
	private static final Pattern onlinestatusPattern = Pattern
			.compile("<td class=\"onlineStatus\">.*?class=\"(.*?)\".*?>(.*?)<");


	
	private static final SimpleDateFormat sdtf = new SimpleDateFormat(
			"d.MMM.yyyy", new Locale("en"));

	public static Vector<User> getFriendlist(GRSession grsession)
			throws ARException, IOException {
		Vector<User> userlist = new Vector<User>();

		UserFactory userfab = UserFactory.getUserFactory(grsession);

		String urlstring = grsession.getGrurl();
		urlstring += grsession.getPhpSessionID();
		urlstring += "/myuser/?sort=2&sortDirection=-1&page=romeo&filterSpecial=all&subPage=&folder=&filterSmiley=&sortBy=4";

		String response = ARRequester.sendRequest(grsession, urlstring, "");

		Matcher useritemMatcher = useritemPattern.matcher(response);

		while (useritemMatcher.find()) {
			String line = useritemMatcher.group(0);
			String uid = null;
			String uname = null;
			String onlinestatus = null;
			Date date = new Date();

			Matcher usernameMatcher = usernamePattern.matcher(line);
			Matcher onlinestatusMatcher = onlinestatusPattern.matcher(line);

			if (usernameMatcher.find()) {
				uid = usernameMatcher.group(1);
				uname = usernameMatcher.group(3);
			}

			if (onlinestatusMatcher.find()) {
				onlinestatus = onlinestatusMatcher.group(2);
				if ("isNotOnline"
						.equalsIgnoreCase(onlinestatusMatcher.group(1))) {
					try {
						date = sdtf.parse(onlinestatus.trim());
					} catch (ParseException e) {
						e.printStackTrace();
					}
				}
			}

			// write information
			if (uid != null) {
				User user = userfab.getUserById(uid);
				user.setUserName(uname);

				user.setOnlineStatus(onlinestatus);
				user.setLastOnlineDate(date);
				userlist.add(user);
			}

		}

		return userlist;
	}

}
